<template>
   <!-- 弹窗组件 -->
   <div class="dialog-box">
      <el-dialog
         v-model="dialogVisible"
         :title="editId ? '编辑供应商' : '新增供应商'"
         width="700"
      >
         <el-form
            :model="supplierDetail"
            :rules="rules"
            ref="formRef"
            label-width="100px"
         >
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="供应商名称"
                     prop="name"
                     required
                  >
                     <el-input
                        v-model="supplierDetail.name"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="供应商级别"
                     prop="supplier_level_id"
                     required
                  >
                     <el-select
                        v-model="supplierDetail.supplier_level_id"
                        placeholder="请选择"
                     >
                        <el-option
                           v-for="item in supplierLevelList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"
                        />
                     </el-select>
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="联系人"
                     prop="contact_person"
                     required
                  >
                     <el-input
                        v-model="supplierDetail.contact_person"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="联系人电话"
                     prop="contact_phone"
                     type="number"
                     required
                  >
                     <el-input
                        v-model="supplierDetail.contact_phone"
                        placeholder="请输入"
                        maxlength="11"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="联系人邮箱"
                     prop="contact_email"
                     required
                  >
                     <el-input
                        v-model="supplierDetail.contact_email"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="联系人职位"
                     prop="contact_position"
                     required
                  >
                     <el-input
                        v-model="supplierDetail.contact_position"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="地区"
                     prop="province"
                     required
                  >
                     <el-cascader
                        style="width: 100%"
                        :options="pcaTextArr"
                        v-model="place"
                        @change="handleRegionChange"
                        placeholder="请选择省市区"
                     >
                     </el-cascader>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="详细地址"
                     prop="address"
                     required
                  >
                     <el-input
                        v-model="supplierDetail.address"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-form-item
               label="备注"
               prop="note"
            >
               <el-input
                  v-model="supplierDetail.note"
                  placeholder="请输入"
               />
            </el-form-item>

            <div class="supply-products">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     供货产品
                  </div>
                  <el-badge
                     class="item"
                     :value="supplierDetail.product_data.length"
                     color="#FFF849"
                     :offset="[-6, -5]"
                  >
                     <el-button @click="openRelatedProducts"> 关联产品 </el-button>
                  </el-badge>
               </div>
               <el-table
                  border
                  :data="supplierDetail.product_data"
                  style="width: 100%"
               >
                  <el-table-column
                     prop="name"
                     label="产品名称"
                     align="center"
                  />
                  <el-table-column
                     prop="no"
                     label="产品编号"
                     align="center"
                  />
                  <el-table-column
                     prop="specification"
                     label="规格型号"
                     align="center"
                  />
                  <el-table-column
                     prop="img"
                     label="产品图片"
                  >
                     <template #default="scope">
                        <div class="image-list">
                           <el-image
                              v-for="(img, index) in scope.row.img"
                              :key="index"
                              :src="img"
                              fit="cover"
                           />
                        </div>
                     </template>
                  </el-table-column>
                  <el-table-column
                     label="操作"
                     width="100"
                     align="center"
                  >
                     <template #default="scope">
                        <el-button
                           type="danger"
                           @click="handleRemoveProduct((scope.row as any).id)"
                           link
                           >移除</el-button
                        >
                     </template>
                  </el-table-column>
               </el-table>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="dialogVisible = false">取消</el-button>
               <el-button
                  color="#626aef"
                  @click="handleSubmit"
               >
                  确定
               </el-button>
            </div>
         </template>
      </el-dialog>
      <RelatedProducts
         ref="relatedProductsRef"
         @SelectRelatedProducts="SelectRelatedProducts"
         :product-data="supplierDetail.product_data"
      />
   </div>
</template>

<script setup lang="ts">
   import { ref, reactive, defineExpose, defineEmits } from "vue";
   import { pcaTextArr } from "element-china-area-data";
   import RelatedProducts from "./RelatedProducts.vue";
   import api from "@/api/index.js";
   import { SupplierDetail, productDataType } from "../suppliersType";
   import { ElMessage } from "element-plus";
   import type { FormInstance } from "element-plus";
   const relatedProductsRef = ref<any>(null);
   const dialogVisible = ref<boolean>(false);
   const formRef = ref<FormInstance>();
   // 省市区选择器
   const place = ref<string[]>([]);
   const handleRegionChange = (value: string[]) => {
      supplierDetail.value.province = value[0];
      supplierDetail.value.city = value[1];
      supplierDetail.value.area = value[2];
   };
   const emit = defineEmits(["refresh"]);
   // 供应商详情
   const supplierDetail = ref<SupplierDetail>({
      id: 0, //供应商ID
      name: "", //供应商名称
      contact_person: "", //联系人名称
      supplier_level_id: 0, //等级ID
      contact_phone: "", //联系人电话
      contact_email: "", //联系人邮箱
      contact_position: "", //联系人职位
      province: "", //供应商地区（省）
      city: "", //供应商地区（市）
      area: "", //供应商地区（区）
      address: "", //供应商详细地址
      note: "", //备注
      product_data: [], // 供货产品
      product_ids: [], // 已选供货产品编号
   });
   const editId = ref<number | null>(null);
   const getSupplierDetail = async () => {
      const res = await api.supplier.supplierDetail({
         id: editId.value,
      });
      if (res.code == 200) {
         supplierDetail.value = res.data;
         // 设置省市区回显数据
         if (supplierDetail.value.province && supplierDetail.value.city && supplierDetail.value.area) {
            place.value = [supplierDetail.value.province, supplierDetail.value.city, supplierDetail.value.area];
         }
      }
   };
   // 移除供货产品
   const handleRemoveProduct = (id: number) => {
      supplierDetail.value.product_data = supplierDetail.value.product_data.filter((item) => item.id !== id);
   };
   // 选择供货产品
   const SelectRelatedProducts = (data: productDataType[]) => {
      const newData = data.filter((item) => {
         const isExist = supplierDetail.value.product_data.some((p) => p.id === item.id);
         return !isExist;
      });

      const duplicateData = data.length - newData.length;
      if (duplicateData > 0) {
         ElMessage.warning(`已过滤${duplicateData}个重复产品`);
      }
      supplierDetail.value.product_data.push(...newData);
   };
   const supplierLevelList = ref<any[]>([]);
   // 获取供应商等级
   const getSupplierLevelList = async () => {
      const res = await api.publicFun.getSupplierLevelList();
      if (res.code == 200) {
         supplierLevelList.value = res.data;
      }
   };
   const openLoading = async (id: number) => {
      dialogVisible.value = true;
      await getSupplierLevelList();
      // 重置表单校验状态
      if (formRef.value) {
         formRef.value.resetFields();
      }
      if (id) {
         // 编辑
         editId.value = id;
         await getSupplierDetail();
      } else {
         editId.value = null;
         // 新增
         supplierDetail.value = {
            product_data: [],
            product_ids: [],
         } as unknown as SupplierDetail;
         // 清空省市区选择
         place.value = [];
      }
   };
   // 关联产品
   const openRelatedProducts = () => {
      relatedProductsRef.value.openLoading();
   };
   const handleSubmit = async () => {
      if (!formRef.value) return;
      await formRef.value.validate(async (valid: boolean) => {
         if (valid) {
            const params = {
               name: supplierDetail.value.name,
               supplier_level_id: supplierDetail.value.supplier_level_id,
               contact_person: supplierDetail.value.contact_person,
               contact_phone: supplierDetail.value.contact_phone,
               contact_email: supplierDetail.value.contact_email,
               contact_position: supplierDetail.value.contact_position,
               province: supplierDetail.value.province,
               city: supplierDetail.value.city,
               area: supplierDetail.value.area,
               address: supplierDetail.value.address,
               note: supplierDetail.value.note,
               product_skus: supplierDetail.value.product_data.map((item) => {
                  return item.id;
               }),
            };
            if (editId.value != null && editId.value) {
               // 编辑
               const res = await api.supplier.supplierEdit({ ...params, id: editId.value });
               if (res.code == 200) {
                  ElMessage.success("编辑成功");
                  dialogVisible.value = false;
                  emit("refresh");
               }
            } else {
               // 新增
               const res = await api.supplier.supplierAdd(params);
               if (res.code == 200) {
                  ElMessage.success("新增成功");
                  dialogVisible.value = false;
                  emit("refresh");
               }
            }
         }
      });
   };

   // 表单验证规则
   const rules = reactive({
      name: [{ required: true, message: "请输入供应商名称", trigger: "blur" }],
      supplier_level_id: [{ required: true, message: "请选择供应商级别", trigger: "change" }],
      contact_person: [
         { required: true, message: "请输入联系人", trigger: "blur" },
         { min: 2, max: 20, message: "联系人长度在2-20个字符之间", trigger: "blur" },
      ],
      contact_phone: [
         { required: true, message: "请输入联系人电话", trigger: "blur" },
         { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
      ],
      province: [{ required: true, message: "请选择地区", trigger: "change" }],
      address: [
         { required: true, message: "请输入详细地址", trigger: "blur" },
         { min: 2, max: 100, message: "详细地址长度在2-100个字符之间", trigger: "blur" },
      ],
      contact_email: [
         { required: true, message: "请输入联系人邮箱", trigger: "blur" },
         { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
      ],
      contact_position: [
         { required: true, message: "请输入联系人职位", trigger: "blur" },
         { min: 2, max: 20, message: "职位长度在2-20个字符之间", trigger: "blur" },
      ],
      product_skus: [{ required: true, message: "请选择供货产品", trigger: "change" }],
      note: [{ max: 200, message: "备注长度不能超过200个字符", trigger: "blur" }],
   });

   defineExpose({
      openLoading,
   });
</script>

<style lang="scss" scoped>
   ::v-deep .el-dialog {
      --el-dialog-padding-primary: 0px;
   }
   ::v-deep .el-dialog__header {
      padding: 10px 16px;
      border-bottom: 1px solid #f0f0f0;
      font-weight: bold;
   }
   ::v-deep .dialog-footer {
      padding: 10px 16px;
      border-top: 1px solid #f0f0f0;
   }
   ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #000;
   }
   ::v-deep .el-dialog__body {
      padding: 10px 10px;
   }
   :deep(.el-form-item__label) {
      justify-content: flex-start;
   }
   :deep(.el-form-item) {
      flex-direction: column;
      margin-bottom: 7px;
   }
   :deep(.el-select__wrapper) {
      background: #fafcfb;
   }
   :deep(.el-badge__content.is-fixed) {
      color: #666;
      border-radius: 3px;
      padding: 4px;
   }
   // :deep(.el-table .cell) {
   //    display: flex;
   //    justify-content: center;
   // }
   :deep(.el-button:hover) {
      color: #6860ff;
      background: #f4f5f7;
   }
   .supply-products {
      margin-top: 20px;
      .title {
         display: flex;
         align-items: center;
         justify-content: space-between;
         margin-bottom: 16px;
         font-weight: bold;
         .title-text {
            display: flex;
            align-items: center;
            .line {
               height: 17px;
               width: 2px;
               border-radius: 12px;
               margin-right: 8px;
               background-color: #6860ff;
            }
         }
      }
   }
   .image-list {
      display: flex;
      gap: 8px;
      .el-image {
         width: 40px;
         height: 40px;
         border-radius: 4px;
      }
   }
</style>
